import os
import os.path

import logging

logger = logging.getLogger(__name__)

def CleanOutputDirectory(graph, output_directory):
  # Seed the output set with the graph files.
  valid_files = set(
      [os.path.join(output_directory, '__graph__/watcher_alive_log'),
       os.path.join(output_directory, '__graph__/watcher_pid'),
       os.path.join(output_directory, '__graph__/watcher_port'),
       os.path.join(output_directory, '__graph__/newgraph.db')])
  # A set to hold all the folders that we have completely cleaned out.
  clean_folders = set()

  logger.info('Walking output folder and cleaning.')
  # Walk the output directory tree, starting at the bottom.
  for dirpath, dirnames, filenames in os.walk(output_directory, topdown=False):
    has_subfile = False
    # Check to see if each of the files is in the valid_files set.
    for filename in filenames:
      file_path = os.path.join(dirpath, filename)
      fsets = list(graph.get_fsets_for_file(file_path))
      if fsets:
        for fset in fsets:
          if fset.gen_rule.valid:
            has_subfile = True
          else:
            logger.debug('Removing ' + file_path)
            os.unlink(file_path) 
      elif file_path in valid_files:
        has_subfile = True
      else:
        os.unlink(file_path) 
    # If there are no valid files in this directory, see if there are any
    # subdirectories.  We are starting at the bottom of the tree, so subfolders
    # will be clean or valid.
    if not has_subfile:
      keep_folder = False
      # Check to see if there are any valid subfolders
      for dirname in dirnames:
        if os.path.join(dirpath, dirname) not in clean_folders:
          keep_folder = True
          break

      # See if the folder is in the graph.
      if not keep_folder:
        fsets = list(graph.get_fsets_for_file(dirpath + '/'))
        if fsets:
          for fset in fsets:
            if fset.gen_rule.valid:
              keep_folder = True
              break

      # If not, delete the subfolder
      if not keep_folder:
        logger.debug('Removing folder ' + dirpath)
        os.rmdir(dirpath)
        clean_folders.add(dirpath)
